package com.itheima.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class RecommendMovementTask {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    MongoTemplate mongoTemplate;


    @Scheduled(cron = "0/30 * * * * ?")
    public void saveRecommendMovement(){

        System.out.println("推荐动态任务开始执行~~~");
        //1.获取所有推荐动态的key
        Set<String> keys = stringRedisTemplate.keys("MOVEMENTS_RECOMMEND_*");

        //2.遍历key的集合,获取每个用户的推荐动态的pid字符串(用","隔开)
        if (CollUtil.isNotEmpty(keys)) {
            for (String key : keys) {

                //注意:保存推荐数据之前,先将之前的推荐数据删除掉,根据用户的id删除推荐
                Long userId = Long.valueOf(key.replace("MOVEMENTS_RECOMMEND_", ""));
                mongoTemplate.remove(new Query(Criteria.where("userId").is(userId)), RecommendMovement.class);

                //2.1 获取value (每个用户的推荐动态的pid字符串)
                String pidStr = stringRedisTemplate.opsForValue().get(key);

                System.out.println(userId+":"+pidStr);

                //2.2 将字符串切割成数组
                String[] pidArr = pidStr.split(",");

                //3.获取每个动态pid,通过pid获取movement对象
                for (String pid : pidArr) {
                    Long pId = Long.valueOf(pid);

                    Movement movement = mongoTemplate.findOne(new Query(Criteria.where("pid").is(pId)), Movement.class);

                    //4.封装成recomendMovement对象,保存中数据库中
                    RecommendMovement recommendMovement = new RecommendMovement();
                    recommendMovement.setCreated(System.currentTimeMillis());
                    recommendMovement.setUserId(userId);
                    recommendMovement.setPid(pId);
                    recommendMovement.setPublishId(movement.getId());
                    recommendMovement.setScore(RandomUtil.randomDouble(70,99));

                    mongoTemplate.save(recommendMovement);
                }

            }
        }

        System.out.println("推荐动态任务结束了!");

    }

}
